
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>摄像头调用示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }
        video {
            width: 100%;
            max-width: 640px;
            background-color: #000;
            border-radius: 8px;
        }
        button {
            padding: 10px 20px;
            margin: 10px;
            font-size: 16px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <h1>摄像头调用演示</h1>
    <video id="video" autoplay></video>
    <div>
        <button id="startButton">开启摄像头</button>
        <button id="stopButton" disabled>停止摄像头</button>
    </div>

    <script>
        const video = document.getElementById('video');
        const startButton = document.getElementById('startButton');
        const stopButton = document.getElementById('stopButton');
        let stream = null;

        // 开启摄像头
        startButton.addEventListener('click', async () => {
            try {
                stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        width: { ideal: 1280 },
                        height: { ideal: 720 },
                        facingMode: "user" // 前置摄像头
                    },
                    audio: false
                });
                video.srcObject = stream;
                startButton.disabled = true;
                stopButton.disabled = false;
            } catch (err) {
                console.error("摄像头访问出错:", err);
                alert("无法访问摄像头: " + err.message);
            }
        });

        // 停止摄像头
        stopButton.addEventListener('click', () => {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                video.srcObject = null;
                startButton.disabled = false;
                stopButton.disabled = true;
            }
        });
    </script>
</body>
</html>
